package main

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/logger"
	"github.com/kataras/iris/middleware/recover"
	"github.com/spf13/viper"
	"irisfarm/app/commons"
	"irisfarm/app/core"
	"irisfarm/app/core/config"
	"irisfarm/app/core/db"
	"irisfarm/app/core/log"
	"irisfarm/app/core/ssl"
	"irisfarm/app/middlewares"
	"irisfarm/routes"
)

func init() {
	// 初始化应用日志
	core.Log = log.New()

	// 初始化配置文件 多个配置文件使用,隔开
	config.New("app", "cors", "database", "iris", "ssl")

	// 初始化数据库
	core.DB = db.New()

	// 初始化mongodb
	//irisfarm.MongoDB = mongo.New()

	// 初始化redis
	//irisfarm.Redis = redis.New()

	// 初始化cors中间件
	core.CorsHandler = middlewares.CorsNew()

	// 初始化jwt中间件
	core.JwtHandler = middlewares.JwtNew()
}

func main() {
	// 运行日志文件
	runLogFile := log.RunLogFile()
	defer runLogFile.Close()

	app := iris.New()

	// 加载recover
	app.Use(recover.New())

	// 追加运行日志文件
	app.Logger().SetLevel(viper.GetString("DebugLevel")).AddOutput(runLogFile)

	// 加载运行日志
	app.Use(logger.New())

	// 加载ssl
	s := ssl.New()
	app.Use(s.Serve)

	// 通用错误处理
	commons.ErrorHandle(app)

	// 加载路由
	routes.ApiRoutes(app)

	// 运行iris
	address := viper.GetString("http.ip") + ":" + viper.GetString("http.port")
	_ = app.Run(iris.Addr(address), iris.WithoutServerError(iris.ErrServerClosed), iris.WithConfiguration(iris.YAML("./configs/iris.yml")))
}
